package com.xz;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author XZ
 * @create 2021-10-18 20:09
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 * 失败
 */
public class _102_二叉树的层序遍历 {
    //失败：
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        levelOrderTraversal(root,lists);
        return lists;
    }

    public void levelOrderTraversal(TreeNode root, List<List<Integer>> lists) {
        if (root == null) return;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);//入队
        int i = 1;
        List<Integer> list = new LinkedList<>();
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();//将每次出队的节点设置为头节点，这里设置的头节点非常关键，是每层递进的起点。
            list.add(node.val);
            i--;
            if (i == 0) {
                List<Integer> listCopy = new LinkedList<>();
                for (Integer integer : list) {
                    listCopy.add(integer);
                }
                lists.add(listCopy);
                list.clear();
                i=queue.size();
            }
            if (node.left != null) {
                queue.offer(node.left);
            }

            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

    //答案
    public List<List<Integer>> levelOrder1(TreeNode root) {
        if(root == null) return new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()){
            int count = queue.size();
            List<Integer> list = new ArrayList<Integer>();
            while(count > 0){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null)
                    queue.add(node.left);
                if(node.right != null)
                    queue.add(node.right);
                count--;
            }
            res.add(list);
        }
        return res;
    }
}